package cn.hchaojie.web.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class DemoHikariDatasource {
	HikariDataSource ds = null;
	
	@Before
	public void init() throws IOException {
//		InputStream is = getClass().getClassLoader().getResourceAsStream("hikari.properties");
//		
//		Properties props = new Properties();
//		props.load(is);	
//		
//		HikariConfig config = new HikariConfig();
//		config.setJdbcUrl(props.getProperty("url"));
//		config.setUsername(props.getProperty("userName"));
//		config.setPassword(props.getProperty("password"));
//		config.setDriverClassName(props.getProperty("driverClass"));
//		ds = new HikariDataSource(config);
		
		HikariConfig config = new HikariConfig("/hikari.properties");
		ds = new HikariDataSource(config);
	}
	
	@Test
	public void testResource() throws IOException {
		// 读properties文件
//		InputStream is = getClass().getResourceAsStream("../../../../hikari.properties");
		InputStream is = getClass().getClassLoader().getResourceAsStream("hikari.properties");
		
		Properties props = new Properties();
		props.load(is);
		
		System.out.println(props.getProperty("userName"));
		System.out.println(props.getProperty("password"));
		System.out.println(props.getProperty("nothing", "meiyou"));
	}
	
	@Test
	public void testInsert() {
		try {
			// 获取连接
			Connection connection = ds.getConnection();
			
			// 发送sql语句
			PreparedStatement ps = connection.prepareStatement("insert into actor (first_name, last_name) values ('宝强', '王')");
			int result = ps.executeUpdate();
			System.out.println("result:" + result);
			// 遍历结果
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testDelete() {
		try {
			// 获取连接
			Connection connection = ds.getConnection();
			
			// 发送sql语句
			PreparedStatement ps = connection.prepareStatement("delete from actor");
			int result = ps.executeUpdate();
			System.out.println("result:" + result);
			// 遍历结果
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
